package com.hrsoft.edi.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 后台当前上下文
 *
 * @author ace
 * @version 2017/9/8
 */
public class BaseContextHandler
{
    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static void set(String key, Object value)
    {
        Map<String, Object> map = threadLocal.get();
        if (map == null)
        {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key)
    {
        Map<String, Object> map = threadLocal.get();
        if (map == null)
        {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void remove()
    {
        threadLocal.remove();
    }

    public static Map<String, Object> getAll()
    {
        return threadLocal.get();
    }

    public static void setLocal(Map<String, Object> context)
    {
        threadLocal.set(context);
    }

    public static void removeKey(String key)
    {
        Map<String, Object> threadLocalMap = threadLocal.get();
        Iterator<String> iterator = threadLocalMap.keySet().iterator();
        while (iterator.hasNext())
        {
            String k = iterator.next();
            if (k.equals(key))
            {
                iterator.remove();
            }
        }
    }
}
